import proj4  from "proj4";
import {register} from 'ol/proj/proj4';
import { Projection,addProjection} from 'ol/proj';
import TileLayer from "ol/layer/Tile.js";
import TDTWMTS from 'ol/source/WMTS.js';
import {getTopLeft, getWidth} from "ol/extent.js";
import {get as getProjection} from "ol/proj.js";
import WMTSTileGrid from "ol/tilegrid/WMTS.js";
import {Group} from "ol/layer.js";


export const registerCGCS2000 = ()=>{
    proj4.defs("EPSG:4490","+proj=longlat +ellps=GRS80 +no_defs +type=crs");
    // 完成2000坐标系在ol中注册
    register(proj4);
    // 由于我们用这个坐标系来加载wmts1.1和1.30的服务，这两种服务支持的坐标系与默认的2000坐标，坐标轴顺序不同，所以需要重新定义一个proj2000
    const proj2000 = new Projection({
        code:"EPSG:4490",
        units: 'degrees',
        axisOrientation: 'neu',
        extent: [-180, -90, 180, 90],
        worldExtent: [-180, -90, 180, 90],
    });
    addProjection(proj2000);
}



const useTDT = (layername,projection,tk) => {
    if(projection==="经纬度投影"){
        registerCGCS2000()
    }
    const projectionMap = {
        "经纬度投影": "EPSG:4490",
        "球面墨卡托投影": "EPSG:3857"
    }

    const layernameMap = {
        "矢量底图": ["vec","cva"],
        "影像底图": ["img","cia"],
        "地形晕渲": ["ter","cta"]
    }

    const matrixSetMap = {
        "经纬度投影": "c",
        "球面墨卡托投影": "w"
    }

    const resolutions = []
    const matrixIds = []

    let width = getWidth(getProjection(projectionMap[projection]).getExtent());

    for (let z = 1; z < 19; z++) {
        resolutions[z] = width / (256 * Math.pow(2, z));
        matrixIds[z] = z;
    }


    const getTdtLayer = (layername) => {
        const tdtlayer = new TileLayer({
            source: new TDTWMTS({
                // url: 'http://t0.tianditu.gov.cn/vec_c/wmts?tk=d06c497b107f57ebd6a0f8fbf967292d',
                url: `http://t0.tianditu.gov.cn/${layername}_${matrixSetMap[projection]}/wmts?tk=${tk}`,
                layer: layername,
                matrixSet:`${matrixSetMap[projection]}`,
                format: 'tiles',
                projection: projection,
                requestEncoding: 'KVP',
                tileGrid: new WMTSTileGrid({
                    origin: getTopLeft(getProjection(projectionMap[projection]).getExtent()),
                    resolutions:resolutions,
                    matrixIds: matrixIds
                }),
            }),
        })
        return tdtlayer
    }
    const layername1 = layernameMap[layername][0]
    const tdtlayer2 = layernameMap[layername][1]

    return new Group({
        layers:[getTdtLayer(layername1),getTdtLayer(tdtlayer2)],
        title:layername,
    })
}


export default useTDT


